<template>
    <div class="repair">
        <van-form
            show-error
            scroll-to-error
            label-width="25vw"
            @submit="onSubmit"
            @failed="onFailed" 
        >
            <my-title>报修信息</my-title>
            <FieldPopupDatePicker v-model:field="formData.gcr_dat1" :required="true" name="gcr_dat1" label="报修日期" :readonly="isReadonly" />
            <van-field 
                v-model="formData.gcr_ex14" 
                :readonly="isReadonly"
                required
                center
                name="gcr_ex14" 
                label="墓位编号"
                placeholder="墓位编号" 
                :rules="[{ required: true, message: '请填写墓位编号' }]"
            />
            <van-field 
                v-model="formData.gcr_ex12" 
                :readonly="isReadonly"
                type="textarea"
                rows="1"
                autosize
                required
                center
                name="gcr_ex12" 
                label="报修内容"
                placeholder="报修内容" 
                :rules="[{ required: true, message: '请填写报修内容' }]"
            />
           
            <van-field 
                required
                center
                name="gcr_ex4" 
                label="报修图片"
                placeholder="报修图片" 
                :rules="[{ required: true, message: '请上传报修图片' }]"

            >
                <template #input>
                    <van-uploader 
                        v-model="dataArr.gcr_ex4"
                        :readonly="isReadonly"
                        :deletable="!isReadonly"
                        :max-count="9" 
                        upload-text="报修图片" 
                        :before-delete="beforeDelete('gcr_ex4')"
                        :before-read="beforeRead" 
                        :after-read="afterRead('gcr_ex4')"
                    />
                </template>
            </van-field>
            <FixedButton v-if="!isReadonly" native-type="submit">提交</FixedButton>
        </van-form>
    </div>
</template>

<script lang="ts" setup>
    import { ref, reactive, markRaw, onBeforeMount } from 'vue'
    import type { Ref, Raw } from 'vue'
    import { useRouter, useRoute } from 'vue-router'
    import { showDialog, showLoadingToast, closeToast, showFailToast  } from 'vant'
    import FixedButton from '@/components/FixedButton.vue'
    import FieldPopupPicker from '@/components/FieldPopupPicker.vue'
    import FieldPopupDatePicker from '@/components/FieldPopupDatePicker.vue'
    import FieldPopupTimePicker from '@/components/FieldPopupTimePicker.vue'
    import FieldPopupEsign from '@/components/FieldPopupEsign.vue'
    import { saveCemeteryRepairApi, fileUploadBase64ExApi, idOrcApi, getRecordDetailsApi } from '@/apis'
    import { compressImg, isCardID } from '@/utils/utils.js'
    import { useStore } from '@/store'

    const router = useRouter()
    const route = useRoute()
    const store = useStore()
    const isReadonly: boolean = route.query?.sh_id ? true : false
    const formData = ref({
        sh_ex2: '',
        gcr_ex14: '',
        gcr_dat1: '',
        gcr_ex12: '',
        gcr_ex4: '',
    })
    const dataArr = reactive({
        gcr_ex4: [], //报修图片
    })
    onBeforeMount(async () => {
        if (isReadonly) {
            console.log('...........')
            // 获取数据
            getRecordDetailsApi({
                sh_id: route.query.sh_id
            }).then(res => {
                formData.value = res.data[0]
                if (formData.value.gcr_ex4) {
                    dataArr.gcr_ex4 = [{
                        url: formData.value.gcr_ex4,
                        isImage: true
                    }]
                }
            })
        }
    })
    const beforeDelete = (data) => {
        return (file, detail) => {
            let arr = formData.value[data].split(',')
            arr.splice(detail.index, 1)
            formData.value[data] = arr.join(',')
            return true
        }
    }
    const beforeRead = (file) => {
        console.log(file)
        if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
            showFailToast('请上传 jpg/png 格式图片');
            return false;
        }
        return true;
    }
    const afterRead = (imgField, isIdOrc = false) => {
        return file => {
            file.status = 'uploading';
            file.message = '上传中...';
            // 执行压缩图片并上传
            let obj = new compressImg(file, afterRead2, imgField, isIdOrc, file )
            // console.log(obj)
            // console.log(obj.getMyf())
            // console.log(obj.getMyfb())
            // console.log(obj.myf)
            // console.log(obj.myfb)
        }
    }
    // 组件方法 获取 流
    const afterRead2 = (imgField, isIdOrc, file, obj) => {
        // failed done 
        // file.status = 'uploading';
        // file.message = '上传中...';
        // file.file: 文件 file.content: base64图片
        console.log(file)
        // let f = new FormData()
        // f.append('file', file.file)
        fileUploadBase64ExApi({
            data: obj,
            sCode: 'kmxbyg'
        }).then(res => {
            // file.status = 'done';
            // file.message = '上传完成';
            console.log(res)

            if (imgField == 'sh_ex36' || imgField == 'sh_ex37') {
                // 拍照识按钮要显示不能设置maxCount=1，不然上传一张图就没了按钮
                if (dataArr[imgField].length > 1) {
                    dataArr[imgField].shift()
                }
                formData.value[imgField] = res[0].url
                // 用过拍照识别后续上传身份证都要进行idOrc验证信息
                if (isIdOrc) {
                    idOrcApi({
                        img: obj
                    }).then(res => {
                        if (res.idcard_number_type == 1) {
                            let obj = res.words_result

                            if (imgField == 'sh_ex36') {
                                formData.value.sh_ex1 = obj['姓名'].words
                                formData.value.sh_ex2 = obj['公民身份号码'].words
                                // formData.value.sh_ex3 = obj['性别'].words
                            } else if (imgField == 'sh_ex37') {
                                formData.value.sh_ex5 = obj['姓名'].words
                                formData.value.sh_ex35 = obj['公民身份号码'].words
                            }
                        } else {
                            throw new Error('身份证验证失败')
                        }
                        file.status = 'done';
                        file.message = '上传完成';
                        
                    }).catch(err => {
                        console.log(err)
                        showFailToast('识别失败')
                        file.status = 'done';
                        file.message = '上传完成';
                    })
                } else {
                    file.status = 'done';
                    file.message = '上传完成';
                }

            } else {
                // formData.value[imgField] = res[0].url
                if (formData.value[imgField]) {
                    formData.value[imgField] = formData.value[imgField].concat(',', res[0].url)
                } else {
                    formData.value[imgField] = formData.value[imgField].concat(res[0].url)
                }
                file.status = 'done';
                file.message = '上传完成';
            }
            
        }).catch(err => {
            file.status = 'failed';
            file.message = '上传失败';
            console.log(dataArr[imgField])
            dataArr[imgField].pop()
            showFailToast('上传失败')
            console.log(err)
        })
    }

    const onFailed = (value) => {
        showDialog({
            title: '提示',
            message: value.errors[0].message
        })
    }
    const onSubmit = async (value) => {
        showLoadingToast({
            message: '加载中...',
            forbidClick: true,
            duration: 0
        });
        
        saveCemeteryRepairApi({
            // data: JSON.stringify(formData.value),
            ...formData.value
        }).then(res => {
            closeToast();
            if (res[0].status == '+OK') {
                showDialog({
                    title: '提示',
                    message: '提交成功！',
                }).then(() => {
                    router.push('/')                         
                });
            } else {
                showDialog({
                    title: '提示',
                    message: res[0].msg,
                })
            }
            
        }).catch(err => {
            closeToast();
            showDialog({
                title: '提示',
                message: '网络异常，请稍后重试！',
            })
        })
    }
</script>
<style lang="scss" scoped>
    .repair {
        height: 100vh;
        overflow: hidden;
        display: flex;
        flex-direction: column;
    }
    :deep(.van-form) {
        // height: 550px;
        // height: 510px;
        flex: 1;
        overflow: scroll;
    }
    .uploader-box {
        border-bottom: 1px solid #999999;
        margin: 6px 15px;
        box-sizing: border-box;
        padding: 0px 0;
        height: 180px;
        overflow: hidden;
        img {
            width: 345px;
            height: 180px;
        }
        // 上传图片后图片大小
        :deep(.van-uploader__preview-image) {
            width: 345px;
            height: 180px;
        }
    }
    .my-card {
        background: #fff;
        border-bottom: 1px solid #efefef;
    }
    .card-price {
        text-align: right;
        font-size: 20px;
        font-weight: bold;
        padding: 10px;
        .card-price-span1 {
            font-size: 15px;
        }
        .card-price-span2 {
            display: inline-block;
            width: 90px;
        }
    }
</style>